<?php
require_once 'lib/controllerWithoutGetOrPost.php';
require_once 'view/standard-personal-noleftbar-top.php';
require_once 'dataformatting.php';


function clearFirstName($val) {
 if($val == "First Name") {
	return "Anonymous";
 } else {
	return $val;
 }
}

function clearSurname($val) { 
 if($val == "Last Name") {
	return "";
 } else {
	return $val;
 }
}

function clearTown($val) {
 if($val == "Town") {
	return "";
 } else {
	return $val;
 }
}

function clipartDefault($val) {
	if($val == null || $val == "") {
		return 0;
	} else {
		return $val;
	}
}

function InsertComment($id, $firstname, $surname,
        $heading, $comment, $citytown, $countryid,
        $clipartid, $email, $db) {
    global $db;
    $sql = <<< EOT
        INSERT INTO
            RemembranceComment (
                PersonID, FirstName, Surname, Heading, Comment,
                CityTown, Email, DateAdded, DateModified,
                Category, CountryID, ClipartID)
            Values (
                %d, '%s', '%s', '%s', '%s',
                '%s', '%s', '%s', '%s',
                %d, %d, %d)
EOT;
    $sql = sprintf($sql,
        intval($id),
        $db->escape(clearFirstName($firstname)),
        $db->escape(clearSurname($surname)),
        $db->escape($heading),
        $db->escape($comment),
        $db->escape(clearTown($citytown)),
        $db->escape($email),
        $db->escape(gmdate("Y-m-j H:i:s", time() + 3600*12)),
        $db->escape(gmdate("Y-m-j H:i:s", time() + 3600*12)),
        1,
        $db->escape($countryid),
        intval(clipartDefault($clipartid))
    );        
    $db->query($sql);	
}
			
function FirstNames($value) {
	if(isset($value) && $value != "") {
		return "<li><span>First Names: </span>".$value."</li>";
	}
}

function KnownAs($value) {
	if(isset($value) && $value != "") {
		return	"<li><span>Known as:</span>".$value."</li>";
	}
}

function LastName($value) {
	if(isset($value) && $value != "") {
		return "<li><span>Last Name:</span>".strtoupper($value)."</li>";
	}
}

function Nee($value) {
	if(isset($value) && $value != "") {
		return " nee ".$value;
	}
	return "";
}

function OtherNames($value, $nee) {
	if((isset($value) && $value != "") || (isset($nee) && $nee != "")) {
		return "<li><span>Other Names:</span>".strtoupper($value).Nee($nee)."</li>";
	}
}

function fullName($firstName, $lastName) {
    return implode(' ', array_filter(array($firstName, $lastName)));
}

function formatdatetime($date) {
	if($date == "0000-00-00 00:00:00") {
		return "";
	}   else {
		return date('d F Y', strtotime(str_replace("&", "&amp;", $date)));
	}
}

function formatdatetime4($date) {
	if($date == "0000-00-00 00:00:00") {
		return "";
	}   else {
		return date('d M Y', strtotime(str_replace("&", "&amp;", $date)));
	}
}


function BirthDate($value) {
	if(isset($value) && $value != "" && $value != "0000-00-00 00:00:00") {
		return "<li><span>Birth Date: </span>".formatdatetime($value)."</li>";
	}
}

function DeathDate($value) {
	if(isset($value) && $value != "" && $value != "0000-00-00 00:00:00") {
		return "<li><span>Death Date: </span>".formatdatetime($value)."</li>";
	}
}

function Age($value, $measure) {
	if(isset($value) && $value != "" && $value != "0") {
		return "<li><span>Age: </span>".$value.$measure."</li>";
	}
}

function Country($value) {
	if(isset($value) && $value != "") {
		return "<li><span>Country: </span>".$value."</li>";
	}
}

function Funeral($id, $value, $db) {
	if(isset($value) && $value != "") {
		$query = "select FuneralDetails.`Web` from FuneralDetails left join FuneralHome on FuneralHome.ID = FuneralDetails.FuneralHomeID where FuneralHomeID = ".$id;
		$result = $db->query($query);
		$returnval = "";
		if($db->rowCount($result)!=0) {
			$row = $db->fetchRow($result);
			$val = $row[0];
			if($val != "" && isset($val)) {
				$returnval = "<li><span>Funeral Home:</span> <a href=\"".$val."\" title=\"\">".$value."</a></li>";
			} else {
				$returnval = "<li><span>Funeral Home:</span> ".$value."</a></li>";	
			}
		} else {
			$returnval = "<li><span>Funeral Home:</span> ".$value."</a></li>";	
		}
 
		$db->free($result);

		return $returnval;
	}
}

function CharityWeb($value, $http) {
	if(isset($http) && $http != "") {
		return "<a href=\"".$http."\">".$value."</a>";
	} else {
		return $value;
	}
}

function Charity($value, $http) {
	if(isset($value) && $value != "") {
		return "<li><span>Charity:</span> ".CharityWeb($value, $http)."</li>";
	}
}

function PublishedNotices($id, $db) {
    if(isset($id) && $id != "") {
        $query = "select count(*) from Publication left join PublicationPerson on Publication.ID = PublicationPerson.PublicationID where PublicationPerson.PersonID = ".$id;
        $result = $db->query($query);
        $returnval = "";
        if($db->rowCount($result)!=0) {
        $row = $db->fetchRow($result);
        $returnval = "<li><span>Published Notices:</span> (<a href=\"personnotices.php?personid=".$id."\">".$row[0]."</a>) Newspapers - <a href=\"personnotices.php?personid=".$id."\">View</a></li>";
    } else {
        $returnval = "<li><span>Published Notices:</span> (0)</li>";
    }
        $db->free($result);
        return $returnval;
    }
}

?>
<script type="text/javascript">
function textCount() {
	elem = document.getElementById('comment');
	if (elem.value.length > 1000) {
		elem.value = elem.value.substring(0, 1000);
	} else {
		var counts = document.getElementById('count');
		counts.innerHTML = elem.value.length;
	}
}

function validate_email(field,alerttxt) {
	with (field) {
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
		if (apos<1||dotpos-apos<2) {
			alert("Please enter a valid email address.");
			return false;
		} else { return true; }
	}
}

function emailconfirm(field1, field2) {
	if(field1.value != field2.value && field1.value.length > 0 && field2.value.length > 0) {
		alert("Please double check that you have entered the same email address in both fields.")
	}
}


</script>
<?php			

if(isset($_GET['personid']) && $_GET['personid'] != "") {
    $agreementCheckbox = false;
    $identicalEmails = false;
    $verifiedCode = false;
    $countrySelected = false;
    $_POSTed = false;
    if($_POST['post'] == "posted") {
        $_POSTed = true;
    //if email addresses don't match.				
        if(!empty($_POST['emailconfirm']) && $_POST['email'] == $_POST['emailconfirm']) {
            $identicalEmails = true;		
        }
    
        if (!empty($_POST['code'])) { 
            require_once 'securimage/securimage.php';
            $img = new Securimage();
            $valid = $img->check($_POST['code']);
            if($valid == true) {
                $verifiedCode = true;
            }				
        }
        
        if(!empty($_POST['agree']) && $_POST['agree'] == "yes") {
            $agreementCheckbox = true;
        }
        
        if(!empty($_POST['country']) && $_POST['country'] != "not") {
            $countrySelected = true;
        }
        
    }
    
    if($agreementCheckbox && $identicalEmails && $verifiedCode && $countrySelected) {
    
        $firstname = $_POST['firstname'];
        $surname = $_POST['surname'];
        if($_POST['anonymous'] == "yes") {
            $firstname = "Anonymous";
            $surname = "";
        }
        
        InsertComment($_GET['personid'], $firstname, $surname, $_POST['heading'], $_POST['comment'], $_POST['citytown'], $_POST['country'], $_POST['clipart'], $_POST['email'], $db);
                //Thank you for posting a message to "Person's name". Back to remembrance page for Person's name.
                
                //comment placed
                
    }
    


    $query = "
    SELECT
        Person.ID,
        Person.FirstNames,
        Person.Surname
    FROM Person 
    WHERE Person.ID = ".intval($_GET['personid']);
    $result = $db->query($query);
    if($db->rowCount($result)!=0) {
        $row = $db->fetch($result);
        $personID = $row['ID'];
        $firstName = $row['FirstNames'];
        $lastName = $row['Surname'];
        $fullName = $firstName . ' ' . $lastName;
        ?>
        <div id="contentarea">
            <ul id="fullbar">
                <?php 
                if(!($agreementCheckbox && $identicalEmails && $verifiedCode && $countrySelected) && $_POSTed == true) {
                    echo '<li class="messageheader"><h2 style=\"color:red\">OOPS, SUBMISSION ERROR - you have  not filled in all the required fields.</h2><ul>';			
                    
                                            
                    if(!$agreementCheckbox) {
                        echo "<li><strong>* <span style=\"color:red\">You must accept the Terms and Conditions in order to have your message submitted.</span></strong></li>";						
                    }
                    
                    if(!$identicalEmails) {
                        echo "<li><strong>* <span style=\"color:red\">The provided email addresses do not match. Please check them.</strong></span></li>";
                    }
                    
                    if(!$verifiedCode) {
                        echo "<li><strong>* <span style=\"color:red\">The verification code you entered is not valid. Please try again.</strong></span></li>";
                    }	
                    
                    if(!$countrySelected) {
                        echo "<li><strong>* <span style=\"color:red\">Please select a country from the drop down.</strong></span></li>";
                    }	
                    echo '</ul></li>';
                            
                }
                
                if($agreementCheckbox && $identicalEmails && $verifiedCode && $countrySelected && $_POSTed) {
                    //Go back to the Remembrance Page for Charlotte Rose Skeet-Shields
                    echo "<li class=\"messageheader\"><a href=\"remembrance.php?personid=".$_GET['personid']."\">Go back to the Remembrance Page for ".$fullName."</a></li>";
                    echo "<li style=\"text-align: center;\"><h2>Thank You</h2><p>Your message has been submitted to the team for approval.</p><p>An email will be sent to <strong>".$_POST['email']."</strong> when the message has been accepted.</p><p><strong>Approving messages can take up to 12 hours.</strong></p></li>";
                    
                } else {
                    require_once 'leaveamessagemain.php';
                            
                }
                ?>
            </ul>
            <ul id="rightbar">
                <li class="linkitem">
                    <?php
                    $query2 = "select count(*) from Publication left join PublicationPerson on Publication.ID = PublicationPerson.PublicationID where PublicationPerson.PersonID = ".$personID;
                    $result2 = $db->query($query2);
                    $query4 = "select `Name`, `DatePublished` from Publication left join PublicationPerson on Publication.ID = PublicationPerson.PublicationID where PublicationPerson.PersonID = ".$personID;
                    $result4 = $db->query($query4);
                    if($db->rowCount($result2)!=0) {
                        $row = $db->fetchRow($result2);
                        echo "<h2><a href=\"#\">Published Notices (".$row[0].")</a></h2>";
                    } else {
                        echo "<h2><a href=\"#\">Published Notices (0)</a></h2>";
                    }

                    echo "<ul>";
                    if($db->rowCount($result4)!=0) {
                        while ($row3 = $db->fetch($result4)) {
                            $pubname = explode("-",$row3['Name']);
                            $pubname = $pubname[2];
                            $query5 = "select `Name` from Newspapers where `ShortName` = '".$pubname."';";
                            $result5 = $db->query($query5);
                            $row = $db->fetchRow($result5);
                            echo "<li>".$row[0]." - ".formatdatetime4($row3['DatePublished'])."</li>";
                        }				
                    }
                    echo "<li class=\"right\"><a href=\"personnotices.php?personid=".$_GET['personid']."\">view all</a></li>";
                    echo "</ul>";			
                                
                    $db->free($result2);			
                    ?>
                </li>
                <li class="linkitem">
                    <a href="support.php" title="Support">Support</a>
                </li>
                <li class="linkitem feature" id="getinspiration">
                        <a href="message_library.php?returnto="<?php echo $_GET['personid']; ?>" rel="external" title="Get inspiration from our Message Library">Get inspiration from<br/>our Message Library</a>
                </li>
                <li class="linkitem">
                    <a href="donate_to_charity.php" title="Donate to a Charity">Donate</a>
                </li>
				<li class="linkitem">
					<span class="new">&nbsp;</span>
					<a href="/alerts.php" title="Book an Alert">Book an Alert</a>
				</li>
                <li class="linkitem">
                    <a href="gift_giving.php" title="Send a Gift">Send a Gift</a>
                </li>				
                <li class="linkitem">
                    <a href="travel.php" title="Make Travel Arrangments">Make Travel Arrangements</a>
                </li>
                <li class="alt">
                    <?php
                    echo "<a title=\"Tell a Friend\" class=\"browsernav_tellfriend\" href=\"mailto:?subject=A Memory Tree has a Remembrance Page open for ".$row['FirstNames'].", ".titleCaseName($row['Surname'])."&body=Hi, I'm letting you know that a Remembrance Page has been opened on www.amemorytree.co.nz website and you can leave a message for free today.  
        Visit http://amemorytree.co.nz/remembrance.php?personid=".$_GET['personid']." to view the page and read other messages.\">Tell a Friend</a><br />";
                    /*<a href="#" title="Printer Friendly" class="browsernav_printerfriendly">Printer Friendly</a><br/>
                    <a href="#" title="Set as my Home Page" class="browsernav_sethomepage">Set as my Home Page</a> */
                    ?>
                </li>
            </ul>
        </div>
        <?php
    }
}
require_once 'view/standard-noads-bottom.php';
?>
